from utils.electrode_ctrl import ElectrodeCtrl
import numpy as np
from time import sleep,time,perf_counter
from utils import pressure_recv_svr

# 22/July/2024: two boards line scan, adjust the scanning velocity, adding the pressure sensor

def sleep_us(us:float):
    sleep(us / 1_000_000)

# Function to busy-wait for a specified number of microseconds
def busy_wait_us(us: float):
    end_time = perf_counter() + us / 1_000_000  # Calculate end time in seconds
    while perf_counter() < end_time:
        pass  # Busy-wait loop

def apply_electrode_stimulus(elec, pattern):
    for line in range(8):
        #print(f'----------正在扫描第{line + 1}行--------------')
        #print('持续扫描1s')
        count = 0

        start_time = perf_counter()  # Record the start time using perf_counter
        while perf_counter() - start_time < 0.05625:  # 持续1秒钟
            # 单点，从左扫到右

            pattern[line, :] = 1
            #print(pattern)
            for index, board in enumerate(elec):
                # 取消板子高阻态
                board.on()
                # print(f' 第{index + 1}个板子,第{i + 1}个电极点')
                # print(pattern)
                board.set_tick(pattern=pattern,
                               pp=100,
                               pw=50,
                               pn=1,
                               bp=100,
                               pulse_type='neg'
                               )

                tick_start_time = perf_counter()
                # print(tick_start_time)
                #busy_wait_us(100)  # Busy-wait for 100 microsecond
                # sleep_us(1000)
                tick_end_time = perf_counter()
                # print(tick_end_time)
                # pattern[line, i] = 0
                board.off()

                # Adjust sleep time based on time taken for other operations
                tick_duration = tick_end_time - tick_start_time
                # print(f"Board {index + 1}, Line {line + 1}, Electrode {i + 1}, Tick duration: {tick_duration}")
            pattern[line, :] = 0

                # print(f"Tick duration: {tick_duration}")

            count += 1
        #print(f'第{line + 1}行扫描完毕')
        #print(f'第{line + 1}行扫描次数：{count}')


if __name__=='__main__':
    frame_open = np.zeros((8,8))
    elec = []

    N_threshold_high = 3500  # threshold for stopping giving the electro stimulus (unit: gram)
    N_threshold_low = 0  # Pressure threshold for starting giving the electro stimulus

    elec.append(ElectrodeCtrl('COM9', 115200, 'com')) # 2号板子（靠近风扇）
    elec.append(ElectrodeCtrl('COM10', 115200, 'com'))  # 1号板子（远离风扇）
    #elec.append(ElectrodeCtrl('COM13', 115200, 'com'))  # 1号板子（远离风扇）

    pattern = np.zeros((8,8))

    # Start the pressure sensor server
    pressure_recv_svr.start_pressure_recv_svr()

    # 新增变量来存储压力数据和记录时间
    pressure_data = []
    record_start_time = None

    # Start the pressure sensor server
    pressure_recv_svr.start_pressure_recv_svr()

    while True:
        sleep(1e-7)
        pressure_g = pressure_recv_svr.global_data
        print(f'Detected Pressure: {pressure_g}')

        # 检查是否需要开始记录压力
        if record_start_time is None and pressure_g > N_threshold_low and pressure_g < N_threshold_high:
            record_start_time = perf_counter()
            print('Pressure is in the normal range, start recording for 15 seconds')

        # 如果已经开始记录，并且时间未超过15秒，则继续记录压力
        if record_start_time and (perf_counter() - record_start_time) < 15:
            pressure_data.append(pressure_g)

        # 检查是否已经记录了15秒
        if record_start_time and (perf_counter() - record_start_time) >= 15:
            # 计算中间10秒的压力平均值
            middle_10s_indices = int((15 - 10) / 2)  # 计算中间10秒的起始索引
            middle_10s_data = pressure_data[middle_10s_indices:-middle_10s_indices]
            average_pressure = np.mean(middle_10s_data)
            print(f'Average pressure over the middle 10 seconds: {average_pressure}')

            # 重置记录状态
            record_start_time = None
            pressure_data = []









        # Monitor the pressure sensor and apply the electro scanning stimulus once the pressure is greater than some threshold
        #if pressure_g> N_threshold_low and pressure_g < N_threshold_high:
        if pressure_g < N_threshold_high:
            #print('Pressure is in the normal range, keep giving the electro stimulus')
            apply_electrode_stimulus(elec, pattern)
        elif pressure_g > N_threshold_high:
            print('Pressure is too high, stop giving the electro stimulus')


